<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class History extends Model
{
    //
    protected $fillable = ['child_id', 'game_id', 'grade_id', 'level', 'category_id', 'device_id', 'agency_id','user_id','start_time', 'end_time', 'use_time', 'start_star', 'end_star', 'result'];
    
    public function getUseTimeAttribute($value)
    {
    	return date("i:s", $value);
    }

    public function child(){
        return $this->belongsTo(Child::class);
    }

    public function game(){
        return $this->belongsTo(Game::class);
    }

    public function device(){
        return $this->belongsTo(Device::class);
    }

    public function grade(){
        return $this->belongsTo(Grade::class);
    }

    public function category(){
        return $this->belongsTo(Category::class);
    }

    public function agency(){
        return $this->belongsTo(Agency::class);
    }
    public function snapshots(){
        return $this->hasMany(Snapshot::class);
    }
    public function user(){
        return $this->belongsTo(User::class);
    }

    /*

     * 拼接查询条件
     *      */
    public static function selectQuery($data){
        return function ($query) use ($data) {
            if(isset($data['agency_id']) && $data['agency_id'] > 0){
                $query->where('agency_id', $data['agency_id']);
            }
            if(isset($data['user_id']) && $data['user_id'] > 0){
                $query->where('user_id', $data['user_id']);
            }
            if(isset($data['child_id']) && $data['child_id'] > 0){
                $query->where('child_id', $data['child_id']);
            }
            if(isset($data['category_id']) && $data['category_id'] > 0){
                $query->where('category_id', $data['category_id']);
            }
            if(isset($data['grade_id']) && $data['grade_id'] > 0){
                $query->where('grade_id', $data['grade_id']);
            }
            if(isset($data['startquerytime']) && $data['startquerytime'] > 0){
                $query->where('start_time','>', $data['startquerytime']);
            }
            if(isset($data['endquerytime']) && $data['endquerytime'] > 0){
                $query->where('start_time','<', $data['endquerytime']);
            }
            if (isset($data['child_name']) && !empty($data['child_name'])) {
                $query->where(function($s) use ($data){
                    $s->whereHas('child', function($item) use ($data){
                        $item->where('name', 'like',  '%' . $data['child_name'] . '%');
                    });
                });
            }
        };
    }
}
